#include"FormData.h"
#include<regex>
#include<iostream>

void FormData::setFormData(const std::string &ct, const std::string &data){
  auto gm = [](const std::smatch &m){return m[0].length() < m[1].length() ? m[0] : m[1];};
  std::smatch m;
  std::regex_search(ct, m, std::regex("(?:---)([A-Za-z0-9]+)"));
  std::string &&b = gm(m);
  std::string::const_iterator itb = data.begin();
  std::string::const_iterator ite = data.end();
  std::smatch mm;
  while(std::regex_search(itb, ite, m, std::regex(b + "[\\S\\s]*?(?=\r\n-*" + b + ")"))){
    auto &f = m[0].first, &s = m[0].second;
    std::regex_search(f, s, mm, std::regex("(?:name=\")([\\S\\s]*?(?=\"))"));
    std::string &&name = gm(mm);
    std::regex_search(f, s, mm, std::regex("(?:[\\S\\s]*?\r\n\r\n)([\\S\\s]*)"));
    auto d = gm(mm);
    if(std::regex_search(f, s, mm, std::regex("(?:filename=\")([\\S\\s]*?(?=\"))"))){
      std::string &&filename = gm(mm);
      files[name] = std::make_shared<MultiFile>();
      files[name]->data << d;
      files[name]->name = filename;
    }else{
      values[name] = d;
    }
    itb = s;
  }
} 
